<?php

namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\Article;
use app\models\Category;
use app\tools\Re;
use Yii;
use yii\helpers\Json;

class ArticleController extends BaseController
{
    /**
     * @param string $type
     * @return array
     */
    public function actionArticleList(){
        $page = Yii::$app->request->post('page', 0);
        $title = Yii::$app->request->post('title', '');
        $article_query = Article::find()->where(['status' => [0,1]]);
        if ($title) {
            $article_query->andWhere(['like', 'title', $title]);
        }
        $article_list = $article_query->orderBy("created_at desc")->limit(Article::PAGE_SIZE)->offset(Article::PAGE_SIZE*$page)->all();
        $article_data = [];
        if ($article_list) {
            foreach ($article_list as $v) {
                $article_data[] = [
                    'id' => $v->id,
                    'title' => $v->title,
                    'cover' => $v->cover,
                    'content' => $v->content,
                    'cate_id' => $v->cate_id,
                    'cate_name' => $v->cate->name,
                    'source' => $v->source,
                    'is_recom' => $v->is_recom,
                    'article_recom' => $v->article_recom,
                    'h5_url' => Yii::$app->params['domain_wap'].'/#/?type=2&id='.$v->id,
                    'status' => $v->status,
                    'created_time' => date("Y-m-d", $v->created_at),
                ];
            }
        }
        return Re::data([
            'data' => $article_data,
            'totalPage' => $article_query->count(),
            'currentPage' => $page,
            'perPage' => Article::PAGE_SIZE
        ]);
    }

    public function actionEditArticle(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        $post['admin_id'] = Yii::$app->user->id;
        return $this->edit(Article::class, $id, $post);
    }

    public function actionChangeArticleStatus(){
        $id = Yii::$app->request->post('id', 0);
        $type = Yii::$app->request->post('type', 1);
        $article = Article::findOne($id);
        if (empty($article)) {
            return Re::data(null, '资讯息读取失败', Re::ERROR);
        }
        if ($type == 1) {
            $article->status = $article->status ? 0 : 1;
        } else if ($type == 2) {
            $article->is_recom = $article->is_recom ? 0 : 1;
        } else if ($type == 3) {
            $article->status = -1;
        } else if ($type == 4) {
          $article->article_recom = $article->article_recom ? 0 : 1;
        } 
        if (!$article->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }
}
